package services

import (
	"GOPAAS/internal/app/model"
	"GOPAAS/internal/utils"
	"gorm.io/gorm"
	"time"
)

type AppGridService struct {
	model.AppGrid
}

func GetAppGridService(aid int64) *AppGridService {
	db = getDB()
	var apps model.AppGrid
	if aid > 0 {
		db.First(&apps, aid)
	}
	return &AppGridService{apps}
}

type AppItem struct {
	Id           int64  `json:"id"`
	Name         string `json:"name"`
	Icon         string `json:"icon"`
	IsActive     bool   `json:"is_active"` //是否有效
	IsFocus      bool   `json:"is_focus"`
	CategoryName string `json:"category_name"` //分类
	TypeGroup    string `json:"type_group"`    //用户类型
	Type         string `json:"type"`          //类型
	Public       bool   `json:"public"`
	ModelId      int64  `json:"model_id"`
	Models       string `json:"models"`
	Domain       string `json:"domain"`
	Context      string `json:"context"`
	DateStart    string `json:"date_start"`
	DateEnd      string `json:"date_end"`
	Url          string `json:"url"`
	UserId       int64  `json:"user_id"`
	UserName     string `json:"user_name"`
}
type IndexApp struct {
	CategoryId   int64     `json:"category_id"`
	CategoryName string    `json:"category_name"`
	Apps         []AppItem `json:"apps"`
}

// GetIndexApps 获取首页应用
func GetIndexApps(search string, user_id int64, company_id int64) (res []IndexApp, err error) {
	db = getDB()
	//内部员工//外网
	q := db.Where("state = ?", "已发布")
	if search != "" {
		q.Where("name like ?", "%"+search+"%")
	}
	if user_id > 0 {
		user_service := GetUserService(user_id)
		user_info, _ := user_service.GetUserInfo()
		getWhere(q, user_service.DepartmentId.Int64, user_info, company_id)
		var d_grid4 []int64
		db.Model(model.AppGridResUsersRel{}).Where("user_id=?", user_id).Pluck("grid_id", &d_grid4)
		q.Where("id in ?", d_grid4)
	} else {
		q.Where("type_group = ?", "外网")
	}
	var apps []model.AppGrid
	s := db.Model(&model.AppGrid{})

	s.Preload("Parent").Preload("User").Preload("User.Partner").Where(q).Order("parent_id,sequence,create_date desc").Find(&apps)
	for _, v := range apps {
		var IsActive = false
		if v.DateStart.Valid && v.DateEnd.Valid {
			if time.Now().After(utils.ForceCorrectTime(v.DateStart.Time)) && time.Now().Before(v.DateEnd.Time.AddDate(0, 0, 1)) {
				IsActive = true
			}
		}
		app_item := AppItem{
			Id:           v.Id,
			Name:         v.Name.String,
			Icon:         GetSimpleImage("app.grid", v.Id, "icon"),
			IsActive:     IsActive,
			IsFocus:      true,
			TypeGroup:    v.TypeGroup.String,
			Type:         v.Type.String,
			Public:       v.Public,
			Url:          v.Url.String,
			ModelId:      v.ModelId.Int64,
			Models:       v.Models.String,
			Domain:       v.Domain.String,
			Context:      v.Context.String,
			DateStart:    utils.NullTimeValueFormat(v.DateStart, "2006-01-02"),
			DateEnd:      utils.NullTimeValueFormat(v.DateEnd, "2006-01-02"),
			UserId:       v.UserId.Int64,
			UserName:     v.User.Partner.Name,
			CategoryName: v.Parent.CompleteName,
		}
		if v.Type.String == "九宫格" {
			cate_exist := false
			for kk, vv := range res {
				if vv.CategoryId == 0 {
					cate_exist = true
					res[kk].Apps = append(res[kk].Apps, app_item)
					break
				}
			}
			if !cate_exist {
				res = append(res, IndexApp{
					CategoryId:   0,
					CategoryName: "九宫格",
					Apps: []AppItem{
						app_item,
					},
				})
			}
		} else {
			cate_exist := false
			for kk, vv := range res {
				if vv.CategoryId == v.ParentId.Int64 {
					cate_exist = true
					res[kk].Apps = append(res[kk].Apps, app_item)
				}
			}
			if !cate_exist {
				res = append(res, IndexApp{
					CategoryId:   v.ParentId.Int64,
					CategoryName: v.Parent.CompleteName,
					Apps: []AppItem{
						app_item,
					},
				})
			}
		}
	}
	return
}
func getWhere(q *gorm.DB, department_id int64, user_info SignRes, company_id int64) {
	//部门应用
	var d_grid, d_grid1, d_grid2, d_grid3 []int64
	db.Model(model.AppGridHrDepartmentRel{}).Where("department_id=?", department_id).Pluck("grid_id", &d_grid1)
	d_grid = append(d_grid, d_grid1...)
	var company_ids = []int64{company_id}
	if company_id == 0 {
		company_ids = user_info.CompanyIds
	}
	//公司应用
	db.Model(model.AppGridResCompanyRel{}).Where("company_id in ?", company_ids).Pluck("grid_id", &d_grid2)
	d_grid = append(d_grid, d_grid2...)
	//指定人员应用 -app_grid_user
	db.Model(model.AppGridUser{}).Where("user_id=?", user_info.Uid).Pluck("grid_id", &d_grid3)
	d_grid = append(d_grid, d_grid3...)
	q.Where("type_group = ? or id in ?", "内部员工", d_grid)
}

// GetAllApps 获取所有应用
func GetAllApps(search string, user_id int64, company_id int64, is_focus bool, page int, limit int) (res []IndexApp, err error) {
	db = getDB()
	//内部员工//外网
	q := db.Where("state = ?", "已发布")
	if user_id > 0 {
		user_service := GetUserService(user_id)
		user_info, _ := user_service.GetUserInfo()
		getWhere(q, user_service.DepartmentId.Int64, user_info, company_id)
		if is_focus {
			var d_grid4 []int64
			db.Model(model.AppGridResUsersRel{}).Where("user_id=?", user_id).Pluck("grid_id", &d_grid4)
			q = q.Where("id in ?", d_grid4)
		}
	} else {
		q.Where("type_group = ?", "外网")
	}
	offset := (page - 1) * limit
	var apps []model.AppGrid
	s := db.Model(&model.AppGrid{})
	if search != "" {
		s.Where("name like ?", "%"+search+"%")
	}
	s.Preload("Parent").Preload("User").Preload("User.Partner").Where(q).Order("parent_id,sequence,create_date desc").Offset(offset).Limit(limit).Find(&apps)
	for _, v := range apps {
		var IsActive = false
		var IsFoucs = false
		if v.DateStart.Valid && v.DateEnd.Valid {
			if time.Now().After(utils.ForceCorrectTime(v.DateStart.Time)) && time.Now().Before(v.DateEnd.Time.AddDate(0, 0, 1)) {
				IsActive = true
			}
		}
		rows := db.Where("user_id=? and grid_id=?", user_id, v.Id).First(&model.AppGridResUsersRel{}).RowsAffected
		if rows > 0 {
			IsFoucs = true
		}
		app_item := AppItem{
			Id:           v.Id,
			Name:         v.Name.String,
			Icon:         GetSimpleImage("app.grid", v.Id, "icon"),
			IsActive:     IsActive,
			IsFocus:      IsFoucs,
			TypeGroup:    v.TypeGroup.String,
			Type:         v.Type.String,
			Public:       v.Public,
			Url:          v.Url.String,
			ModelId:      v.ModelId.Int64,
			Models:       v.Models.String,
			Domain:       v.Domain.String,
			Context:      v.Context.String,
			DateStart:    utils.NullTimeValueFormat(v.DateStart, "2006-01-02"),
			DateEnd:      utils.NullTimeValueFormat(v.DateEnd, "2006-01-02"),
			UserId:       v.UserId.Int64,
			UserName:     v.User.Partner.Name,
			CategoryName: v.Parent.CompleteName,
		}
		cate_exist := false
		for kk, vv := range res {
			if vv.CategoryId == v.ParentId.Int64 {
				cate_exist = true
				res[kk].Apps = append(res[kk].Apps, app_item)
			}
		}
		if !cate_exist {
			res = append(res, IndexApp{
				CategoryId:   v.ParentId.Int64,
				CategoryName: v.Parent.CompleteName,
				Apps: []AppItem{
					app_item,
				},
			})
		}
	}
	return
}

// FocusApp 关注应用
func FocusApp(user_id int64, grid_ids []int64) (err error) {
	var au model.AppGridResUsersRel
	var aus []model.AppGridResUsersRel
	db = getDB()
	db.Where("user_id=? and grid_id in ?", user_id, grid_ids).Delete(au)
	for _, v := range grid_ids {
		aus = append(aus, model.AppGridResUsersRel{
			v, user_id,
		})
	}
	err = db.Create(&aus).Error
	return
}

// RemoveUserApp 移除用户关注应用
func (a AppGridService) RemoveUserApp(user_id int64) (err error) {
	var au model.AppGridResUsersRel
	db = getDB()
	err = db.Where("grid_id=? and user_id=?", a.Id, user_id).Delete(&au).Error
	return
}

type AppOpensService struct {
	model.AppOpens
}

func GetAppOpensService(aid int64) *AppOpensService {
	db = getDB()
	var app_opens model.AppOpens
	if aid > 0 {
		db.First(&app_opens, aid)
	}
	return &AppOpensService{app_opens}
}

type AppOpensAd struct {
	Id       int64  `json:"id"`
	Name     string `json:"name"`
	Type     string `json:"type"`
	Sequence int    `json:"sequence"`
	Url      string `json:"url"`
	Node     string `json:"node"`
	Body     string `json:"body"`
}
type AppOpensResult struct {
	Id      int64        `json:"id"`
	Name    string       `json:"name"`
	Details []AppOpensAd `json:"details"`
}

// GetAppOpens 获取开屏广告
func GetAppOpens(host string) (result *AppOpensResult, err error) {
	result = new(AppOpensResult)
	db = getDB()
	now_date := time.Now().Format("2006-01-02")
	var app_open model.AppOpens
	err = db.Where("date_start<=? and date_end>=?", now_date, now_date).Order("date_start desc").First(&app_open).Error
	if app_open.Id > 0 {
		result.Id = app_open.Id
		result.Name = app_open.Name
		var detail = make([]AppOpensAd, 0)
		attach_service := GetAttachService(0)
		var ads []model.AppOpensAd
		db.Where("order_id=? and active=true", app_open.Id).Order("sequence").Find(&ads)
		for _, v := range ads {
			var url = v.Url
			if v.Url == "" && (v.Type == "images" || v.Type == "video") {
				attach, _ := attach_service.GetAttach("app.opens.ad", v.Id, "files")
				if attach.Type == "binary" {
					url = "http://" + host + GetAttach("app.opens.ad", v.Id, attach.Checksum)
				} else {
					url = attach.Url
				}
				url = url + "&preview=1"
			}
			detail = append(detail, AppOpensAd{
				Id:       v.Id,
				Name:     v.Name,
				Type:     v.Type,
				Sequence: v.Sequence,
				Url:      url,
				Body:     v.Body,
				Node:     v.Node,
			})
		}
		result.Details = detail
	}
	return
}
